package com.java.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.java.enums.BorrowerStatusEnum;
import com.java.enums.IntegralEnum;
import com.java.exceptioin.Assert;
import com.java.mapper.*;
import com.java.pojo.entity.*;
import com.java.pojo.vo.*;
import com.java.result.ResponseEnum;
import com.java.service.BorrowInfoService;
import com.java.service.BorrowerAttachService;
import com.java.service.BorrowerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.java.service.DictService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 借款人 服务实现类
 * </p>
 *
 * @author Helen
 * @since 2021-07-08
 */
@Service
public class BorrowerServiceImpl extends ServiceImpl<BorrowerMapper, Borrower> implements BorrowerService {

    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private BorrowerMapper borrowerMapper;

    @Resource
    private BorrowerAttachMapper borrowerAttachMapper;

    @Resource
    private BorrowerAttachService borrowerAttachService;

    @Resource
    private DictService dictService;

    @Resource
    private UserIntegralMapper userIntegralMapper;

    @Resource
    private BorrowInfoMapper borrowInfoMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveBorrowerByUserId(BorrowerVo borrowerVo, Long userId) {
        //
        UserInfo userInfo = userInfoMapper.selectById(userId);

        Borrower borrower = new Borrower();
        BeanUtils.copyProperties(borrowerVo,borrower);
        borrower.setUserId(userId);
        borrower.setName(userInfo.getName());
        borrower.setIdCard(userInfo.getIdCard());
        borrower.setMobile(userInfo.getMobile());
        borrower.setStatus(BorrowerStatusEnum.AUTH_RUN.getStatus());//认证中的一个状态
        borrowerMapper.insert(borrower);
        //
        List<BorrowerAttach> borrowerAttachList = borrowerVo.getBorrowerAttachList();
        borrowerAttachList.stream().forEach(borrowerAttach->{
            borrowerAttach.setBorrowerId(borrower.getId());
            borrowerAttachMapper.insert(borrowerAttach);
        });

        //更新userinfo的认证状态
        userInfo.setBorrowAuthStatus(BorrowerStatusEnum.AUTH_RUN.getStatus());
        userInfoMapper.updateById(userInfo);
    }

    //查询当前用户认证状态
    @Override
    public Integer getStatus(Long userId) {
        //从borrower根据userId查找status
        QueryWrapper<Borrower> wrapper = new QueryWrapper<>();
        wrapper.select("status").eq("user_id",userId);
        List<Object> objects = borrowerMapper.selectObjs(wrapper);
        if(objects.size() == 0){
            return BorrowerStatusEnum.NO_AUTH.getStatus();
        }
        Integer status = (Integer)objects.get(0);
        return status;
    }

    //借款人列表
    @Override
    public IPage selectPage(Integer pageNum, Integer pageSize, String keywords) {
        Page<Borrower> objectPage = new Page<>(pageNum, pageSize);
        QueryWrapper<Borrower> wrapper = new QueryWrapper<>();
        if(StringUtils.isEmpty(keywords)){
            return borrowerMapper.selectPage(objectPage, null);
        }

        wrapper.like("name",keywords)
                .or().like("mobile",keywords)
                .or().like("id_card",keywords)
                .orderByDesc("id");
        IPage<Borrower> page = borrowerMapper.selectPage(objectPage, wrapper);
        return page;
    }

    //获取借款人详情
    @Override
    public BorrowerDetailVo getBorrowerDetail(Long userId) {

        Borrower borrower = borrowerMapper.selectById(userId);

        BorrowerDetailVo borrowerDetailVo = new BorrowerDetailVo();
        BeanUtils.copyProperties(borrower,borrowerDetailVo);

        //是否结婚
        borrowerDetailVo.setMarry(borrower.getMarry()?"是":"否");
        //性别
        borrowerDetailVo.setSex(borrower.getSex()==1?"男":"女");

        //计算下拉列表选中内容
        String education = dictService.getNameByParentDictCodeAndValue("education", borrower.getEducation());
        String industry = dictService.getNameByParentDictCodeAndValue("industry", borrower.getIndustry());
        String income = dictService.getNameByParentDictCodeAndValue("income", borrower.getIncome());
        String returnSource = dictService.getNameByParentDictCodeAndValue("returnSource", borrower.getReturnSource());
        String contactsRelation = dictService.getNameByParentDictCodeAndValue("relation", borrower.getContactsRelation());

        //设置下拉列表选中内容
        borrowerDetailVo.setEducation(education);
        borrowerDetailVo.setIndustry(industry);
        borrowerDetailVo.setIncome(income);
        borrowerDetailVo.setReturnSource(returnSource);
        borrowerDetailVo.setContactsRelation(contactsRelation);

        String status = BorrowerStatusEnum.getMsgByStatus(borrower.getStatus());
        borrowerDetailVo.setStatus(status);

        List<BorrowerAttachVo> borrowerAttachList = borrowerAttachService.getBorrowerAttachList(userId);
        borrowerDetailVo.setBorrowerAttachVOList(borrowerAttachList);

        return borrowerDetailVo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void approve(BorrowerAproveVo borrowerAproveVo) {
        //获取当前borrower对象
        Borrower borrower = borrowerMapper.selectById(borrowerAproveVo.getBorrowerId());
        //设置借款人审批状态
        borrower.setStatus(borrowerAproveVo.getStatus());
        //获取用户userId
        Long userId = borrower.getUserId();
        borrowerMapper.updateById(borrower);
        UserInfo userInfo = userInfoMapper.selectById(userId);
        //用户基本积分
        Integer  baseIntegral= userInfo.getIntegral();
        //风控给的积分
        Integer userInfoIntegral = borrowerAproveVo.getInfoIntegral();
        //用户当前的积分
        Integer currentIntegral = baseIntegral+=userInfoIntegral;
        //身份证信息是否正确 30
        UserIntegral userIntegral = new UserIntegral();

        userIntegral.setUserId(userId);
        userIntegral.setIntegral(userInfoIntegral);
        userIntegral.setContent("基本信息");
        userIntegralMapper.insert(userIntegral);

        if(borrowerAproveVo.getIsCarOk()){
            userIntegral.setUserId(userId);
            userIntegral.setIntegral(IntegralEnum.BORROWER_IDCARD.getIntegral());
            userIntegral.setContent(IntegralEnum.BORROWER_IDCARD.getMsg());
            //更新
            userIntegralMapper.insert(userIntegral);
            //用户当前积分累加
            currentIntegral+=IntegralEnum.BORROWER_IDCARD.getIntegral();
        }

        //车辆信息是否正确 60
        if(borrowerAproveVo.getIsCarOk()){
            userIntegral = new UserIntegral();
            userIntegral.setUserId(userId);
            userIntegral.setIntegral(IntegralEnum.BORROWER_CAR.getIntegral());
            userIntegral.setContent(IntegralEnum.BORROWER_CAR.getMsg());
            //更新
            userIntegralMapper.insert(userIntegral);
            //用户当前积分累加
            currentIntegral+=IntegralEnum.BORROWER_CAR.getIntegral();
        }

        //房产证信息是否正确 100
        if(borrowerAproveVo.getIsHouseOk()){
            userIntegral = new UserIntegral();
            userIntegral.setUserId(userId);
            userIntegral.setIntegral(IntegralEnum.BORROWER_HOUSE.getIntegral());
            userIntegral.setContent(IntegralEnum.BORROWER_HOUSE.getMsg());
            //更新
            userIntegralMapper.insert(userIntegral);
            //用户当前积分累加
            currentIntegral+=IntegralEnum.BORROWER_HOUSE.getIntegral();
        }

        //计算后的总积分 更新到userinfo表中
        userInfo.setIntegral(currentIntegral);
        //设置用户认证状态
        userInfo.setBorrowAuthStatus(borrowerAproveVo.getStatus());
        //更新用户
        userInfoMapper.updateById(userInfo);
    }

    //获取借款信息
    @Override
    public Map<String, Object> show(Long id) {

        Map<String, Object> map = new HashMap<>();
        BorrowInfo borrowInfo = borrowInfoMapper.selectById(id);
        BorrowerInfoVo borrowerInfoVo = new BorrowerInfoVo();
        String returnMethod = dictService.getNameByParentDictCodeAndValue("returnMethod", borrowInfo.getReturnMethod());
        String moneyUse = dictService.getNameByParentDictCodeAndValue("moneyUse", borrowInfo.getMoneyUse());
        BeanUtils.copyProperties(borrowInfo,borrowerInfoVo);
        borrowerInfoVo.setReturnMethodStr(returnMethod);
        borrowerInfoVo.setMoneyUseStr(moneyUse);
        map.put("borrow",borrowerInfoVo);

        Long userId = borrowInfo.getUserId();
        QueryWrapper<Borrower> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        Borrower borrower = borrowerMapper.selectOne(wrapper);
        BorrowerDetailVo borrowerDetailVo = new BorrowerDetailVo();
        BeanUtils.copyProperties(borrower,borrowerDetailVo);

        String education = dictService.getNameByParentDictCodeAndValue("education", borrower.getEducation());
        String industry = dictService.getNameByParentDictCodeAndValue("industry", borrower.getIndustry());
        String income = dictService.getNameByParentDictCodeAndValue("income", borrower.getIncome());
        String returnSource = dictService.getNameByParentDictCodeAndValue("returnSource", borrower.getReturnSource());
        String relation = dictService.getNameByParentDictCodeAndValue("relation", borrower.getContactsRelation());

        //性别
        borrowerDetailVo.setSex(borrower.getSex()==1?"男":"女");
        borrowerDetailVo.setMarry(borrower.getMarry()?"是":"否");
        if(borrower.getStatus()==0){
            borrowerDetailVo.setStatus("未认证");
        }else if(borrower.getStatus()==1){
            borrowerDetailVo.setStatus("认证中");
        }else if(borrower.getStatus()==-1){
            borrowerDetailVo.setStatus("认证失败");
        }else{
            borrowerDetailVo.setStatus("认证通过");
        }
        borrowerDetailVo.setEducation(education);
        borrowerDetailVo.setIndustry(industry);
        borrowerDetailVo.setIncome(income);
        borrowerDetailVo.setReturnSource(returnSource);
        borrowerDetailVo.setContactsRelation(relation);
        map.put("borrowInfo",borrowerDetailVo);
        return map;
    }

}
